import { Text, View, Image, TextInput, StyleSheet, Button, FlatList, Modal, TouchableHighlight } from "react-native"
import React, { useEffect, useState } from "react"
import { useAuth } from "../context/AuthProvider";

const Request = (props) => {
    const navigation = props.children["navigate"]
    const [modalVisible, setModalVisible] = useState(false);
    const [modalVisible1, setModalVisible1] = useState(false);
    const [page, setPage] = useState(1);
    const [list, setList] = useState([]);
    const [list1, setList1] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const [text, setText] = useState('')
    const { user } = useAuth()
    const onFinish = () => {
        setModalVisible(false)
    }
    const onFinish1 = () => {
        setModalVisible1(false)
    }
    const putpinglun = (name, e, id) => {
        // 用来匹配显示评论
        // 评论应该显示在我评论的作品下边
        let id1 = e._dispatchInstances._debugOwner._debugOwner.pendingProps.id
        // console.log(id1);
        if (id == id1) {
            setModalVisible1(!modalVisible1);
        }
        fetch('http://10.7.89.174:3000/fputpinglun', {
            method: 'POST',
            body: JSON.stringify({
                userName: name,
                pinglunName: user.userName
            })
        }).then(res => res.json())
            .then(res => {
                // console.log(res);
                setList1(res.List)
                // console.log(list1);
            })
    }
    useEffect(() => {
        {/*需要在数据库里先插入数据然后进行显示，插入是在pullrequest中实现的
        但是需要先插入评论然后再进行显示评论*/}
        fetch('http://10.7.89.174:3000/request',
            {
                method: 'POST',
                // body: JSON.stringify({
                //     userName: user.userName
                // })
            })
            .then(res => res.json())
            .then(res => {
                // console.log(res);
                setRefreshing(false)
                if (page == 1) {
                    setList(res.List)
                } else {
                    setList([...list, ...res.List])
                }
            })
    }, [page])
    const post = (name, e, id) => {
        // console.log(name,e,id);
        let id1 = e._dispatchInstances._debugOwner._debugOwner.pendingProps.id
        // console.log(id1);
        if (id == id1) {
            setModalVisible(!modalVisible);
        }
        // 用来向数据库提交评论
        fetch('http://10.7.89.174:3000/pinglun',
            {
                method: 'POST',
                // 评论的数据
                body: JSON.stringify({
                    text: text,
                    pinglunName: user.userName,
                    userName: name
                })
            })
            .then(res => res.json())
            .then(res => {
                // console.log(res);
                // setList([...list,...res.List])
                // console.log(list);
            })
    }
    const onEnd = () => {
        setPage(page + 1)
    }
    const onRefresh = () => {
        setRefreshing(true);
        setPage(1);
    }
    const Chat = (name) => {
        fetch("http://10.7.89.174:3000/fchat", {
            method: "POST",
            body: JSON.stringify({
                userName: user.userName,
                AuserName: name
            })
        })
            .then(res => res.json())
            .then(res => {
                // console.log(res);
                // 不能跳转
                if (res.code == 200) {
                    navigation('Chat')
                }
                if(res.code==400){
                    alert('就别和自己聊了')
                }
            })
    }
    const renderItem = ({ item }) => (
        <View key={item.requestId}>
            <View>
                <View style={{ width: 50, height: 50, marginTop: "5%" }}>
                    {/* 用户头像可以在users中查询，然后把数据放入message中，但是需要一个变量来确定这个用户 */}
                    <Image source={{ uri: 'data:image/jpeg/jpg;base64,'+item.avatarUrl }}
                        style={{ width: 50, height: 50, borderRadius: 50, }} />
                </View>
                <Text style={{ marginLeft: 60, marginTop: -40, fontSize: 20 }}>{item.userName}</Text>
                <Text style={{ marginLeft: 380, marginTop: -30, fontSize: 15 }}>
                    {item.requestDate}
                </Text>
                <View style={{ width: '100%', height: 100 }}>
                    <Text style={{ marginTop: 30, marginLeft: 5 }}>{item.requestText}</Text>
                </View>
                {/* 用户上传的图片显示 */}
                <View style={{ width: 250, height: 250, marginTop: "-5%", marginBottom: '2%' }}>
                    <Image source={{ uri: 'data:image/jpeg/jpg;base64,' + item.base64 }}
                        style={{ width: 250, height: 250, marginLeft: 10 }}
                    ></Image>
                </View>
                {/* 把输入的评论传到后台然后再显示出来可能需要写两个flatlist(但是评论就没有办法放在下面了，
                    所以需要把评论和发布信息放到一个数据库，这样就能再item中找到需要的信息)
                    但是怎么去改变显示的样式是一个问题 */}
                {/* 现在有个问题我想评论的文字会出现在每个输入框下面
                    怎么确定评论的输入框
                    需要查询评论框的indexOf也就是第几个评论框和它的id比较如果相等可以输入修改，不相等就不变
                     */}
                {/* 用来操作上传也需要确认点击的按钮，然后调用方法
                    这个评论的内容显示的时候需要用到查询，但是通过什么查询 */}
                {
                    JSON.stringify(user) == "{}"
                        ? (<>
                            <View style={{ flex: 2, flexDirection: "row", marginTop: '2%' }}>
                                <Button title="评论" id={item.requestId} onPress={() => { alert('未登录去登录'); navigation("Login") }} ></Button>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="显示评论" id={item.requestId} onPress={() => { alert('未登录去登录'); navigation("Login") }} ></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="跟买家聊天" style={{ borderRadius: 100 }} onPress={() => { alert('未登录去登录'); navigation("Login") }}></Button>
                                </View>
                            </View>
                        </>)
                        : (<>
                            <View style={{ flex: 2, flexDirection: "row", marginTop: '2%' }}>
                                <Button title="评论" id={item.requestId} onPress={(e) => post(item.userName, e, item.requestId)} ></Button>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="显示评论" id={item.requestId} onPress={(e) => putpinglun(item.userName, e, item.requestId)} ></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                        <Button title="跟买家聊天" style={{ borderRadius: 100 }}        
                                        onPress={() => {Chat(item.userName)}}
                                        ></Button>                                   
                                </View>
                            </View>
                        </>)
                }

            </View>
        </View>
    )
    return (
        <View>
            <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible}
                onRequestClose={() => {
                    setModalVisible(!modalVisible);
                    onFinish
                }}
            >
                <View style={styles.centeredView} >
                    <View style={styles.modalView}>
                        <TextInput
                            placeholder="评论"
                            style={styles.modalText}
                            onChangeText={(text) => { setText(text) }}
                            value={text}
                        ></TextInput>
                        <TouchableHighlight
                            style={styles.openButton}
                            onPress={() => {
                                setModalVisible(!modalVisible);
                            }}
                        >
                            <Button
                                block
                                shape='round'
                                type="primary"
                                htmlType="submit"
                                title="发布评论"
                                onPress={onFinish}
                            >
                            </Button>
                        </TouchableHighlight>
                    </View>
                </View>
            </Modal>
            {/* 用来展示评论 */}
            <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible1}
                onRequestClose={() => {
                    setModalVisible1(!modalVisible1);
                    onFinish1
                }}
            >
                <View style={styles.centeredView} >
                    <View style={styles.modalView}>
                        <View>
                            {

                                list1.map(item => {
                                    return <View style={{ flex: 3, flexDirection: "row" }}>
                                        <Text>用户：{item["pinglunName"]}</Text>
                                        <Text style={{ marginLeft: "3%" }}>{item["pinglun"]}</Text>
                                        <Text style={{ marginLeft: "3%" }}>
                                            {item["pinglunDate"]}
                                        </Text>
                                    </View>
                                }
                                )
                            }
                        </View>
                        <TouchableHighlight
                            style={styles.openButton}
                            onPress={() => {
                                setModalVisible(!modalVisible1);
                            }}
                        >
                            <Button
                                block
                                type="primary"
                                htmlType="submit"
                                title="关闭评论"
                                onPress={onFinish1}
                                color={"orange"}
                            >
                            </Button>
                        </TouchableHighlight>
                    </View>
                </View>
            </Modal>
            < FlatList
                ListEmptyComponent={<Text>暂无数据</Text>}
                onRefresh={onRefresh}
                refreshing={refreshing}
                data={list}
                renderItem={renderItem}
                onEndReached={onEnd}
                keyExtractor={item => item.id}
            />
        </View>
    )
}
const styles = StyleSheet.create({
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: "25%"
    },
    modalView: {
        width: 300,
        height: "50%",
        margin: 20,
        backgroundColor: "white",
        borderRadius: 20,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    openButton: {
        margin: "auto",
        padding: '8%',
        // backgroundColor:"orange"
    },
    textStyle: {
        color: "white",
        fontWeight: "bold",
        textAlign: "center"
    },
    modalText: {
        width: 100,
        height: '10%',
        marginBottom: 15,
        textAlign: "center"
    }
});
export default Request